import { useCallback, useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import { AtButton, AtModal, AtModalAction, AtModalContent, AtToast } from 'taro-ui';
import { useDispatch, useSelector } from 'react-redux';
import TopIcon, { EIcon, IconTypeArray } from '../../components/top-icon/index.weapp';
import { TStateType } from '../../redux/reducers/index';
import * as ActionTypes from '../../redux/action/types';
import { TAssigneeUserInfo, TUserInfo, TUserLink } from '../../types';
import { EStatus } from '../../utils';
import Card from '../../components/card/index.weapp';
import { StatusCard } from './statueCard/index.weapp';

import './index.scss';

const Home = () => {
  const dispatch = useDispatch();
  const userInfo: TUserInfo = useSelector((state: TStateType) => state.userInfo);
  const assigneeUserInfoState: TAssigneeUserInfo = useSelector(
    (state: TStateType) => state.assigneeUserInfo
  );
  const [dayCount, setDayCount] = useState(1);
  const [isOpenLoginModal, setIsOpenLoginModal] = useState(false);
  const [topIconName, setTopIconName] = useState('hetao');
  const [openId, setOpenId] = useState('');
  const [openIdList, setOpenIdList] = useState(['']);
  const [isOpenToast, setIsOpenToast] = useState(false);
  const [isNewUser, setIsNewUser] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isOpenBirthdayToast, setIsOpenBirthdayToast] = useState(false);
  const [birthdayMessage, setBirthdayMessage] = useState('');

  const getJoblist = useCallback(() => {
    Taro.cloud.callFunction({
      name: 'getjoblist',
      data: {
        openId,
        // 可以用来获取其他用户的planlist，目前没用到
        assigneeOpenId: assigneeUserInfoState.openId
      },
      success: function (res: any) {
        dispatch({
          type: ActionTypes.RESOLVE_GET_JOBLIST,
          payload: res.result.data
        });
        setIsLoading(false);
      },
      fail: function (err) {
        console.log(err);
      }
    });
  }, [assigneeUserInfoState.openId, dispatch, openId]);

  const handleLogin = useCallback(() => {
    Taro.getUserProfile({
      lang: 'zh_CN',
      desc: '获取你的昵称、头像、地区及性别',
      success: response => {
        const wxUserInfo = response.userInfo;
        // setUserNickName(wxUserInfo.nickName);
        const newUserInfo = {
          avatarUrl: wxUserInfo.avatarUrl,
          gender: wxUserInfo.gender,
          nickName: wxUserInfo.nickName,
          openId,
          signUpDate: new Date(),
          userLink: ''
        };

        Taro.cloud.callFunction({
          name: 'adduserinfo',
          data: {
            newUserInfo
          },
          success: function () {
            dispatch({
              type: ActionTypes.SET_USERINFO,
              payload: newUserInfo
            });
          },
          fail: function (err) {
            console.log(err);
          }
        });
        if (wxUserInfo.nickName === '乌镇粉牛奶') {
          const birthdayDate = new Date('2022/10/12');
          const currentDate = new Date(new Date().toLocaleDateString());
          if (birthdayDate.getTime() === currentDate.getTime()) {
            setIsOpenBirthdayToast(true);
            setBirthdayMessage('你来了, 那么祝你生日快乐, 欢迎来到pria');
          } else {
            const perDay = (currentDate.getTime() - birthdayDate.getTime()) / 24 / 60 / 60 / 1000;
            setIsOpenBirthdayToast(true);
            setBirthdayMessage(`你来了, 那么祝你${perDay}天前生日快乐, 欢迎来到pria`);
          }
        }
        dispatch({
          type: ActionTypes.SET_USERINFO_PERMISSION,
          payload: true
        });
        getJoblist();
      },
      fail: () => {
        console.error('您拒绝了请求');
        return;
      }
    });
    setIsOpenLoginModal(false);
    setIsNewUser(false);
  }, [dispatch, getJoblist, openId]);

  useEffect(() => {
    if (isNewUser) {
      setIsOpenLoginModal(true);
    } else if (openId && openIdList.length > 0 && userInfo.openId) {
      getJoblist();
    }
  }, [getJoblist, isNewUser, openId, openIdList.length, userInfo.openId]);

  useEffect(() => {
    if (openId && openIdList.length > 0 && !isNewUser) {
      dispatch({
        type: ActionTypes.SET_USERINFO_PERMISSION,
        payload: true
      });
    } else {
      dispatch({
        type: ActionTypes.SET_USERINFO_PERMISSION,
        payload: false
      });
    }
  }, [dispatch, isNewUser, openIdList, openId]);

  useEffect(() => {
    if (userInfo.signUpDate) {
      const userDay = new Date(userInfo.signUpDate);
      const currentDate = new Date();
      setDayCount(Math.ceil((currentDate.getTime() - userDay.getTime()) / 1000 / 60 / 60 / 24));
    }
  }, [userInfo.signUpDate]);

  useEffect(() => {
    renderRandomIcon();
  }, []);

  useEffect(() => {
    Taro.cloud.callFunction({
      name: 'login',
      data: {},
      success: (res: any) => {
        const curOpenId = res.result.openid;
        setOpenId(curOpenId);
        // 获取所有用户的openid
        Taro.cloud.callFunction({
          name: 'getusersopenid',
          success: function (openids: any) {
            const usersOpenId = openids.result.data.map((item: any) => item.openId);
            setOpenIdList(usersOpenId);
            if (!usersOpenId.includes(curOpenId)) {
              setIsNewUser(true);
            } else {
              // 对于已注册的用户获取其用户信息
              setIsNewUser(false);
              Taro.cloud.callFunction({
                name: 'getuserinfo',
                data: {
                  openId: curOpenId
                },
                success: function (userInfoRes: any) {
                  const curUserInfo = userInfoRes.result.data[0];
                  dispatch({
                    type: ActionTypes.SET_USERINFO,
                    payload: curUserInfo
                  });
                  // 用户已经和其他用户关联，获取关联信息
                  if (curUserInfo.userLink) {
                    Taro.cloud.callFunction({
                      name: 'getuserlink',
                      data: {
                        userLink: curUserInfo.userLink
                      },
                      success: function (userLinkRes: any) {
                        const userLinkList: TUserLink = userLinkRes.result.data[0];
                        const assigneeUserOpenId = userLinkList.userGroup.filter(
                          item => item !== curOpenId
                        )[0];
                        // 获取关联用户信息
                        Taro.cloud.callFunction({
                          name: 'getuserinfo',
                          data: {
                            openId: assigneeUserOpenId
                          },
                          success: function (assigneeUserInfoRes: any) {
                            const assigneeUserInfo = assigneeUserInfoRes.result.data[0];
                            dispatch({
                              type: ActionTypes.SET_ASSIGNEEUSERINFO,
                              payload: {
                                avatarUrl: assigneeUserInfo.avatarUrl,
                                nickName: assigneeUserInfo.nickName,
                                openId: assigneeUserInfo.openId
                              }
                            });
                            // 用户和关联用户之间同步关联信息
                            if (assigneeUserInfo.userLink !== userLinkList._id) {
                              Taro.cloud.callFunction({
                                name: 'updateuserinfo',
                                data: {
                                  _id: assigneeUserInfo._id,
                                  userInfo: {
                                    userLink: userLinkList._id
                                  }
                                }
                              });
                            }
                          },
                          fail: function (err) {
                            console.log(err);
                          }
                        });
                      },
                      fail: function (err) {
                        console.log(err);
                      }
                    });
                  }
                },
                fail: function (userInfoRes) {
                  console.log(userInfoRes);
                }
              });
            }
          }
        });
      }
    });
  }, [dispatch]);

  const renderRandomIcon = () => {
    setTopIconName(IconTypeArray[Math.floor(Math.random() * IconTypeArray.length)]);
  };

  const toListClickHandle = useCallback(() => {
    Taro.switchTab({ url: '/pages/list/index' });
  }, []);

  return (
    <View className='list'>
      <View className='header'>
        <Text className='header-des'>元气满满的一天~</Text>
        <TopIcon type={EIcon.TopIcon} name={topIconName} onClick={() => renderRandomIcon()} />
      </View>
      <View className='header-day-container'>
        <Text className='header-day'>{dayCount}</Text>
        <View>天</View>
      </View>
      <Card isLoading={isLoading} />
      <View className='plan-details'>
        <Text className='plan-details-header'>- 计划详情 -</Text>
        <View className='plan-details-status'>
          <View className='plan-details-box'>
            <StatusCard status={EStatus.NoStart} lable='no start' backgroundColor='#F5FAEE' />
          </View>
          <View className='plan-details-box'>
            <StatusCard status={EStatus.InProgress} lable='in progress' backgroundColor='#D6E4FD' />
          </View>
        </View>
        <View className='plan-details-status'>
          <View className='plan-details-box'>
            <StatusCard status={EStatus.Resolved} lable='resolved' backgroundColor='#EBF8DF' />
          </View>
          <View className='plan-details-box'>
            <StatusCard status={EStatus.Ready} lable='ready' backgroundColor='#FDEFEC' />
          </View>
        </View>
        <View className='plan-details-status'>
          <View className='plan-details-box'>
            <StatusCard status={EStatus.Closed} lable='closed' backgroundColor='#E6F9F4' />
          </View>
          <View className='plan-details-box' style={{ width: '50%' }}></View>
        </View>
      </View>
      <AtButton
        type='primary'
        size='small'
        circle
        className='job-list-btn'
        onClick={() => toListClickHandle()}
      >
        Plan List
      </AtButton>
      <AtModal isOpened={isOpenLoginModal}>
        <AtModalContent>需要获取你的性别、头像和昵称</AtModalContent>
        <AtModalAction>
          <Button onClick={() => setIsOpenLoginModal(false)}>取消</Button>
          <Button onClick={() => handleLogin()}>确定</Button>
        </AtModalAction>
      </AtModal>
      <AtToast
        isOpened={isOpenToast}
        text='You do not have permission.'
        onClose={() => {
          setIsOpenToast(false);
        }}
      ></AtToast>
      <AtToast
        isOpened={isOpenBirthdayToast}
        text={birthdayMessage}
        onClose={() => {
          setIsOpenToast(false);
        }}
      ></AtToast>
    </View>
  );
};
export default Home;
